package com.vercon.common.wifi;

import static android.content.Context.CONNECTIVITY_SERVICE;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.SupplicantState;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Parcelable;

import com.vercon.common.utils.LogUtils;

/**
 * 参考
 * https://blog.csdn.net/qq_27634797/article/details/79447514
 */
public class NetworkReceiver extends BroadcastReceiver {

    public static final String TAG = "NetworkReceiver";

    public static boolean isConnect;
    public static boolean isOpen;

    /**
     * wifi连接状态
     */
    // 密码错误
    public static final int STATE_PASSWORD_ERROR = 1;
    // 连接成功
    public static final int STATE_CONNECT_SUCCESS = 2;
    // 连接失败
    public static final int STATE_CONNECT_FAILD = 3;
    // 正在获取ip地址
    public static final int STATE_CONNECT_GET_IP = 4;
    // 正在连接
    public static final int STATE_CONNECT_ING = 5;

    /**
     * wifi的打开与关闭
     */
    // 正在停止WIFI
    public static final int WIFI_STATE_DISABLING = 1;
    // 已停止WIFI
    public static final int WIFI_STATE_DISABLED = 2;
    // 正在打开WIFI
    public static final int WIFI_STATE_ENABLING = 3;
    // 已开启WIFI
    public static final int WIFI_STATE_ENABLED = 4;

    @Override
    public void onReceive(Context context, Intent intent) {
        if (WifiManager.SUPPLICANT_STATE_CHANGED_ACTION.equals(intent.getAction())) {
            // 密码错误广播,是不是正在获得IP地址
            int linkWifiResult = intent.getIntExtra(WifiManager.EXTRA_SUPPLICANT_ERROR, -1);
            if (linkWifiResult == WifiManager.ERROR_AUTHENTICATING) {
                // 密码错误
                LogUtils.d(TAG, "密码错误");
                //ToastUtils.showToast(context.getResources().getString(R.string.wifi_password_error));
            }
            SupplicantState supplicantState = intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE);
            NetworkInfo.DetailedState state = WifiInfo.getDetailedStateOf(supplicantState);
            switch (state) {
                case IDLE:
                    //正在连接 准备开始数据连接设置
                    LogUtils.d(TAG, "IDLE");
                    ConnectivityManager connectManager = (ConnectivityManager) context.getSystemService(CONNECTIVITY_SERVICE);
                    NetworkInfo activeNetworkInfo = null;
                    if (connectManager != null) {
                        activeNetworkInfo = connectManager.getActiveNetworkInfo();
                    }
                    if (activeNetworkInfo == null) {

                    }
                    break;
                case SCANNING:
                    // 正在搜索可用的接入点。
                    LogUtils.d(TAG, "SCANNING");
                    break;
                case CONNECTING:
                    // 正在建立数据连接。
                    LogUtils.d(TAG, "CONNECTING");
                    //ToastManager.instance().error(context.getResources().getString(R.string.wifi_connecting));
                    //EventBus.getDefault().post(new WifiConnectStateEvent().setState(STATE_CONNECT_ING));
                    break;
                case OBTAINING_IPADDR:
                    // 等待来自DHCP服务器的响应，以便分配IP地址信息。
                    LogUtils.d(TAG, "OBTAINING_IPADDR");
                    //ToastManager.instance().success("正在获取IP");
                    break;
                case CONNECTED:
                    // IP通信应该是可用的。
                    LogUtils.d(TAG, "CONNECTED");
                    break;
                case SUSPENDED:
                    // IP流量暂停
                    LogUtils.d(TAG, "SUSPENDED");
                    break;
                case DISCONNECTED:
                    // IP流量不可用。
                    LogUtils.d(TAG, "DISCONNECTED");
//                    ToastUtils.showToast(context.getString(R.string.wifi_no_net));
                    break;
                case DISCONNECTING:
                case FAILED:
                    // 当前正在断开数据连接。
                    // 尝试连接失败。
                    LogUtils.d(TAG, "FAILED");
                    //ToastUtils.showToast(context.getString(R.string.net_work_failed));
                    break;
            }
        } else if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(intent.getAction())) {
            // 监听wifi的打开与关闭，与wifi的连接无关
            int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 0);
            switch (wifiState) {
                case WifiManager.WIFI_STATE_DISABLING:
                    LogUtils.d(TAG, "正在停止wifi");
//                    ToastUtils.showToast(context.getResources().getString(R.string.wifi_stopping));

                    break;
                case WifiManager.WIFI_STATE_DISABLED:
                    LogUtils.d(TAG, "已停止wifi");
//                    ToastUtils.showToast(context.getResources().getString(R.string.wifi_stop));

                    break;
                case WifiManager.WIFI_STATE_ENABLING:
                    LogUtils.d(TAG, "正在打开wifi");
//                    ToastUtils.showToast(context.getResources().getString(R.string.wifi_openning));

                    break;
                case WifiManager.WIFI_STATE_ENABLED:
                    LogUtils.d(TAG, "已打开wifi");
//                    ToastUtils.showToast(context.getResources().getString(R.string.wifi_open));

                    break;
            }
        } else if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(intent.getAction())) {
            // 监听wifi的连接状态即是否连上了一个有效无线路由
            Parcelable parcelableExtra = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
            if (null != parcelableExtra) {
                // 获取联网状态的NetWorkInfo对象
                NetworkInfo networkInfo = (NetworkInfo) parcelableExtra;
                //获取的State对象则代表着连接成功与否等状态
                NetworkInfo.State state = networkInfo.getState();
                //判断网络是否已经连接
                boolean isConnected = state == NetworkInfo.State.CONNECTED;
                if(!isConnect && isConnected && isOpen){
                    //ToastUtils.showToast(context.getString(R.string.net_work_success));
                }
                isConnect = isConnected;
            }
        }

    }

    @SuppressWarnings("unused")
    private String getConnectionType(int type) {
        String connType = "";
        if (type == ConnectivityManager.TYPE_MOBILE) {
            connType = "移动网络";
        } else if (type == ConnectivityManager.TYPE_WIFI) {
            connType = "WIFI网络";
        }
        return connType;
    }

    public static class WifiConnectStateEvent {
        public int state;//1密码错误，2:连接成功，3:连接失败

        private WifiConnectStateEvent setState(int state) {
            this.state = state;
            return this;
        }
    }

    public static class WifiEnableStateEvent {
        public int anableState;//

        public WifiEnableStateEvent(int anableState) {
            this.anableState = anableState;
        }
    }

    public static class NetWorkStateEvent {
        public boolean haveNetwork;

        public NetWorkStateEvent(boolean haveNetwork) {
            this.haveNetwork = haveNetwork;
        }
    }
}
